<?php

namespace app\classroom\model;

use think\Db;
use think\Model;
use tree\Tree;

class ClassroomModel extends Model
{
    public function classroomCategoryTree($selectId = 0, $currentCid = 0)
    {
        $where = ['delete_time' => 0];
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }
        $categories = $this->order("list_order ASC")->where($where)->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        $newCategories = [];
        foreach ($categories as $item) {
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";

            array_push($newCategories, $item);
        }
        $tree->init($newCategories);
        $str     = '<option value=\"{$id}\" {$selected}>{$spacer}{$name}</option>';
        $treeStr = $tree->getTree(0, $str);
        return $treeStr;
    }

    /**
     * 获取教室
     * @param array $filter
     * @param array $order
     * @param int $limit
     * @param $query
     * @return \think\Paginator
     */
    public function getClassroom($filter=[], $order=[], $limit=10, $query)
    {
        //默认条件
        $where = [
            'c.delete_time' => ['eq', 0] //未删除
        ];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        //默认排序
        $sort = ['c.id'=>'desc'];
        if(!empty($order) && is_array($order)){
            $sort = array_merge($order,$sort);
        }

        //分页url额外参数
        $page_query['query'] = [];
        if(!empty($query) && is_array($query)){
            $page_query['query'] = $query;
        }

        $data = $this->alias('c')->field('c.*,sc.name as campus_name')
            ->join('school sc','c.school_id=sc.id')
            ->where($where)
            ->order($sort)
            ->paginate($limit,false,$page_query);

        return $data;
    }

    /**
     * 编辑教室
     * @param array $data
     * @return bool
     */
    public function editClassroom($data=[])
    {
        $result = true;
        $id = intval($data['id']);

        $oldClassroom = $this->where('id', $id)->find();
        if(!isset($oldClassroom->id)){
            $result = false;
        }else{
            self::startTrans();
            try{
                $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

                self::commit();
            }catch(\Exception $e){
                self::rollback();
                $result = false;
            }
        }

        return $result;
    }

    /**
     * 通过字段获取教室
     * @param array $filter
     * @return array|false|\PDOStatement|string|Model
     */
    public function getClassroomByField($filter=[])
    {
        //默认条件
        $where = [
            'create_time' => ['>', 0],
            'delete_time' => ['eq', 0] //未删除
        ];
        if(!empty($filter) && is_array($filter)){
            $where = array_merge($where,$filter);
        }

        $obj = $this->where($where)->find();

        return $obj;
    }

    /**
     * @param $id
     * @param $cur_time
     * @return bool
     */
    public function deleteClassroom($id, $cur_time)
    {
        $result = true;
        if(empty($id)){
            $result = false;
        }else{
            if(empty($cur_time)){
                //当前时间
                $cur_time = time();
            }
            if(is_array($id)){
                //批量删除
                $rooms = $this->where(['id' => ['in', $id]])->select();
                self::startTrans();
                try{
                    $this->where(['id' => ['in', $id]])->update(['delete_time' => $cur_time]);

                    foreach($rooms as $value){
                        $data = [
                            'object_id'   => $value['id'],
                            'create_time' => $cur_time,
                            'table_name'  => 'classroom',
                            'name'        => $value['name']
                        ];
                        //扔进垃圾站
                        Db::name('recycleBin')->insert($data);
                    }

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }else{
                //单一删除
                self::startTrans();
                try{
                    $res = $this->where(['id' => $id])->find();
                    $data = [
                        'object_id'   => $res['id'],
                        'create_time' => $cur_time,
                        'table_name'  => 'classroom',
                        'name'        => $res['name']
                    ];
                    $this->where(['id' => $id])->update(['delete_time' => $cur_time]);
                    Db::name('recycleBin')->insert($data);

                    self::commit();
                }catch(\Exception $e){
                    self::rollback();
                    $result = false;
                }
            }
        }

        return $result;
    }


}